﻿using DAL.Engine.Interface;
using System.Collections.Generic;
using System.Linq;

namespace DAL.Repository
{
    public abstract class MemoryRepository<TEntity, TKey> : IRepository<TEntity, TKey>
       where TEntity : IEntity<TKey>
    {
        private readonly IList<TEntity> _collection = new List<TEntity>();

        public TEntity Get(TKey id)
        {
            return _collection.FirstOrDefault(e => e.Id != null && e.Id.Equals(id));
        }

        public IEnumerable<TEntity> GetAll()
        {
            return _collection.ToList();
        }

        public void Save(TEntity entity)
        {
            if (entity.IsNew)
            {
                _collection.Add(entity);
            }
            else
            {
                var index = _collection.IndexOf(entity);
                _collection[index] = entity;
            }
        }

        public void Delete(TKey id)
        {
            _collection.Remove(Get(id));
        }
    }
}

